import { NTooltip, NIcon, createDiscreteApi } from 'naive-ui';
import {
    TrashOutline,
    CreateOutline,
    DocumentTextOutline
} from '@vicons/ionicons5';
import { deleteByIds, queryValue } from '@/api/public';
import { ref, h, computed } from 'vue';

export default ({ props, onEdit, editData }) => {
    const loading = ref(false);
    const showDrawer = ref(false);
    const tableDataOrigin = ref([]);
    const checkedRowKeys = ref([]);
    const searchKey = ref('');
    const tableData = computed(() => {
        if (props.searchFields.length) {
            return tableDataOrigin.value.filter(item => {
                const p = props.searchFields.some(key => {
                    return item[key] && item[key].includes(searchKey.value);
                });
                return p;
            });
        }
        return tableDataOrigin.value;
    });
    const pagination = ref({
        page: 1,
        pageSize: 20,
        itemCount: tableData.value.length,
        showSizePicker: true,
        showQuickJumper: true,
        pageSizes: [10, 20, 50, 100],
        prefix({ itemCount }) {
            return `共 ${itemCount} 条`;
        },
        onChange: page => {
            pagination.value.page = page;
        },
        onUpdatePageSize: pageSize => {
            pagination.value.pageSize = pageSize;
            pagination.value.page = 1;
        }
    });

    const columns = computed(() => [
        {
            type: 'selection',
            fixed: 'left'
        },
        ...props.tableColumns,
        {
            title: '操作',
            key: 'actions',
            width: props.showDetails ? 100 : 80,
            fixed: 'right',
            render(row) {
                const actionList = [
                    renderTooltipIcon(
                        '编辑',
                        CreateOutline,
                        { class: 'edit' },
                        { onClick: () => onEdit(row) }
                    ),
                    renderTooltipIcon(
                        '删除',
                        TrashOutline,
                        { class: 'delete' },
                        { onClick: () => handleConfirm([row._id]) }
                    )
                ];
                if (props.showDetails)
                    actionList.unshift(
                        renderTooltipIcon(
                            '详情',
                            DocumentTextOutline,
                            { class: 'details' },
                            { onClick: () => onDetails(row) }
                        )
                    );
                return h(
                    'div',
                    {
                        class: 'action-container'
                    },
                    actionList
                );
            }
        }
    ]);
    const { message, dialog } = createDiscreteApi(['message', 'dialog']); //异步函数

    // 渲染tooltip
    const renderTooltipIcon = (text, icon, props, event) => {
        return h(
            NTooltip,
            {
                placement: 'bottom'
            },
            {
                trigger: () =>
                    h(
                        NIcon,
                        {
                            size: 20,
                            ...props,
                            ...event
                        },
                        { default: () => h(icon) }
                    ),
                default: () => [text]
            }
        );
    };
    const rowKey = row => row._id;

    const onDetails = row => {
        editData.value = row;
        showDrawer.value = true;
    };
    // 删除
    const onDelete = ids => {
        deleteByIds(props.tableName, ids).then(() => {
            message.success('操作成功');
            init();
        });
    };
    // 删除提示
    const handleConfirm = ids => {
        dialog.warning({
            title: '警告',
            content: '此操作将删除该数据，确定继续？',
            positiveText: '确定',
            negativeText: '取消',
            onPositiveClick: () => {
                onDelete(ids);
            },
            onNegativeClick: () => {
                message.info('再考虑考虑~');
            }
        });
    };

    // 表格勾选
    const handleCheck = rowKeys => {
        checkedRowKeys.value = rowKeys;
    };

    const init = () => {
        tableDataOrigin.value = [];
        loading.value = true;
        queryValue(props.tableName)
            .then(res => {
                tableDataOrigin.value = res;
            })
            .finally(() => {
                loading.value = false;
            });
    };
    init();

    return {
        columns,
        loading,
        tableData,
        searchKey,
        pagination,
        showDrawer,
        checkedRowKeys,
        init,
        rowKey,
        onDelete,
        handleCheck,
        handleConfirm
    };
};
